package com.example.demo.service.impl;

import com.example.demo.entity.Policy;
import com.example.demo.mapper.PolicyMapper;
import com.example.demo.service.PolicyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.example.demo.exception.bizException.BizException;

import java.time.LocalDateTime;

/**
* <p>
*  服务实现类
* </p>
*
* @author cy
* @since 2020-11-07
*/
@Slf4j
@Service
public class PolicyServiceImpl extends ServiceImpl<PolicyMapper, Policy> implements PolicyService {

    @Override
    public Page<Policy> listPolicysByPage(int page, int pageSize, String factor) {
        log.info("正在执行分页查询policy: page = {} pageSize = {} factor = {}",page,pageSize,factor);
        QueryWrapper<Policy> queryWrapper =  new QueryWrapper<Policy>().like("title", factor).orderByDesc("pub_time");
        Page<Policy> result = super.page(new Page<>(page, pageSize),queryWrapper);
        log.info("分页查询policy完毕: 结果数 = {} ",result.getRecords().size());
        return result;
    }

    @Override
    public Policy getPolicyById(int id) {
        log.info("正在查询policy中id为{}的数据",id);
        Policy policy = super.getById(id);
        log.info("查询id为{}的policy{}",id,(null == policy?"无结果":"成功"));
        return policy;
    }

    @Override
    public int insertPolicy(Policy policy) {
        log.info("正在插入policy");
        policy.setPubTime(LocalDateTime.now());
        if (super.save(policy)) {
            log.info("插入policy成功,id为{}",policy.getPolicyId());
            return policy.getPolicyId();
        } else {
            log.error("插入policy失败");
            throw new BizException("添加失败");
        }
    }

    @Override
    public int deletePolicyById(int id) {
        log.info("正在删除id为{}的policy",id);
        if (super.removeById(id)) {
            log.info("删除id为{}的policy成功",id);
            return id;
        } else {
            log.error("删除id为{}的policy失败",id);
            throw new BizException("删除失败[id=" + id + "]");
        }
    }

    @Override
    public int updatePolicy(Policy policy) {
        log.info("正在更新id为{}的policy",policy.getPolicyId());
        if (super.updateById(policy)) {
            log.info("更新d为{}的policy成功",policy.getPolicyId());
            return policy.getPolicyId();
        } else {
            log.error("更新id为{}的policy失败",policy.getPolicyId());
            throw new BizException("更新失败[id=" + policy.getPolicyId() + "]");
        }
    }

}
